package com.edu.admin.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

/**
 * 日期处理
 * 
 * @author Wangjiong
 * 
 */
public class DateUtils {
	/** 时间格式(yyyy-MM-dd) */
	public final static String DATE_PATTERN = "yyyy-MM-dd";
	/** 时间格式(yyyy-MM-dd HH:mm:ss) */
	public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";


	public static String format(Date date) {
		return format(date, DATE_PATTERN);
	}

	public static String format(Date date, String pattern) {
		if (date != null) {
			SimpleDateFormat df = new SimpleDateFormat(pattern);
			return df.format(date);
		}
		return null;
	}
	
	/**
	 * 字符串转时间
	 * @return
	 */
	public static Date stringToDate(String strDate, String pattern) {
		if (StringUtils.isBlank(strDate)) {
			return null;
		}

		DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
		return fmt.parseLocalDateTime(strDate).toDate();
	}

	/**
	 * 获取系统当前日期
	 * @return
	 */
	public static String getToday() {
		SimpleDateFormat df = new SimpleDateFormat(DATE_PATTERN);
		return df.format(new Date());
	}
	
	/**
	 * 获取系统当前时间
	 * @return
	 */
	public static String getNowTime() {
		SimpleDateFormat df = new SimpleDateFormat(DATE_TIME_PATTERN);
		return df.format(new Date());
	}
	
	/**
	 *  获取今年是哪一年
	 * @return
	 */
	public static Integer getNowYear() {
		Date date = new Date();
		GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
		gc.setTime(date);
		return Integer.valueOf(gc.get(1));
	}
 
	/**
	 *  获取本月是哪一月
	 * @return
	 */
	public static int getNowMonth() {
		Date date = new Date();
		GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
		gc.setTime(date);
		return gc.get(2) + 1;
	}
	
	/**
	 *  返回某个日期后几年的日期
	 * @param year
	 * @param i
	 * @return
	 */
	public static String getAfterYear(String year, int i) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        Date date = sdf.parse(year);
        Calendar cal = new GregorianCalendar();
		cal.setTime(date);
		cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + i);
		return sdf.format(cal.getTime());
	}
	
	/**
	 * 将日期格式进行转换
	 * @param date
	 * @param oldPattern
	 * @param newPattern
	 * @return
	 */
	public static String changePattern(String date,String oldPattern,String newPattern){
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(oldPattern);
			Date parse = sdf.parse(date);
			SimpleDateFormat sdf2 = new SimpleDateFormat(newPattern);
			String format = sdf2.format(parse);
			return format;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
